import React, { useState } from 'react';
import {
  AppBar,
  Toolbar,
  Typography,
  Button,
  Tooltip,
} from '@mui/material';
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import CloudDownloadIcon from '@mui/icons-material/CloudDownload';
import ErrorIcon from '@mui/icons-material/ErrorOutline';
import { useFlowStore } from '../../store/flowStore';
import { useExportHandler } from '../../hooks/useExportHandler';
import { useImportHandler } from '../../hooks/useImportHandler';

interface AppHeaderProps {
  onProblemsPanelToggle: (open: boolean) => void;
}

/**
 * 应用顶部导航栏组件
 * 包含应用标题、导入/导出按钮和问题面板切换按钮
 */
export const AppHeader: React.FC<AppHeaderProps> = ({ onProblemsPanelToggle }) => {
  const { nodes, errors } = useFlowStore();
  const { handleExport } = useExportHandler();
  const { handleImport } = useImportHandler();
  const [isProblemsPanelOpen, setIsProblemsPanelOpen] = useState(false);

  const handleProblemsPanelToggle = () => {
    const newState = !isProblemsPanelOpen;
    setIsProblemsPanelOpen(newState);
    onProblemsPanelToggle(newState);
  };

  return (
    <AppBar position="fixed" sx={{ zIndex: (theme) => theme.zIndex.drawer + 1 }}>
      <Toolbar>
        <Typography variant="h6" noWrap component="div" sx={{ flexGrow: 1 }}>
          行为树编辑器
        </Typography>
        {/* 根据节点数量显示导入或导出按钮 */}
        {nodes.length > 0 ? (
          <Tooltip title="导出行为树">
            <Button
              color="inherit"
              startIcon={<CloudDownloadIcon />}
              onClick={handleExport}
              sx={{ mr: 1 }}
            >
              导出
            </Button>
          </Tooltip>
        ) : (
          <Tooltip title="从文件导入行为树">
            <Button
              color="inherit"
              startIcon={<CloudUploadIcon />}
              onClick={handleImport}
            >
              导入
            </Button>
          </Tooltip>
        )}
        {/* 问题面板切换按钮 */}
        <Tooltip title="显示/隐藏问题面板">
          <Button
            color="inherit"
            startIcon={<ErrorIcon />}
            onClick={handleProblemsPanelToggle}
            sx={{ ml: 1 }}
          >
            问题 ({errors.length})
          </Button>
        </Tooltip>
      </Toolbar>
    </AppBar>
  );
};

